package com.monitor.methods;


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.monitor.methods.tcpmethod.Scan;
import com.monitor.persistence.Port;

public class TCPMethod implements Method{

	private InetAddress address;
	private int threadAmount = 20;
	private int start;
	private int stop;
	private static int threadStopped = 0;
	private List<Port> values = new LinkedList<Port>();
	
	public TCPMethod(String address, int start, int stop) throws UnknownHostException {
		this.address = InetAddress.getByName(address);
		this.start = start;
		this.stop  = stop;
	}
	
	@Override
	public void startMonitor() {
		long timeStart = Calendar.getInstance().getTimeInMillis();
		int difference = stop-start;
		if(difference < threadAmount)
			threadAmount = difference+1;
		for (int i=0; i < threadAmount; i++){
			Scan scan = new Scan(start+i*(difference)/threadAmount, start+(i+1)*(difference)/threadAmount, address, values);
			Thread thread = new Thread(scan);
			thread.start();
		}
		while(true){
			if(threadStopped == threadAmount)
				break;
		}
		viewResults();
		long timer = (Calendar.getInstance().getTimeInMillis()-timeStart)/1000;
		System.out.println("Zajelo czasu: "+ timer/60 +" minut "+timer%60+" sekund");
	}
	
	private void viewResults(){
		System.out.println("Otwarte porty: ");
//		List<Port> sortedList = asSortedList(values);
		for(Port port : values){
			System.out.println("Port "+port.getNumber()+" service: "+port.getService());
		}
	}
	

	public synchronized static void signThreadStopped(){
		threadStopped++;
	}
}
